package com.yizhilu.os.edu.service.impl.user;

import com.yizhilu.os.common.constants.MemConstans;
import com.yizhilu.os.common.contoller.SingletonLoginUtils;
import com.yizhilu.os.common.util.UserAgentUtil;
import com.yizhilu.os.core.entity.PageEntity;
import com.yizhilu.os.core.service.cache.MemCache;
import com.yizhilu.os.core.service.gain.GuidGeneratorService;
import com.yizhilu.os.core.util.ObjectUtils;
import com.yizhilu.os.core.util.Security.PurseSecurityUtils;
import com.yizhilu.os.core.util.StringUtils;
import com.yizhilu.os.core.util.web.WebUtils;
import com.yizhilu.os.edu.constants.enums.AccountStatus;
import com.yizhilu.os.edu.constants.enums.IntegralKeyword;
import com.yizhilu.os.edu.constants.enums.ReqChanle;
import com.yizhilu.os.edu.constants.enums.UserExpandFrom;
import com.yizhilu.os.edu.dao.user.UserDao;
import com.yizhilu.os.edu.dao.user.UserExpandDao;
import com.yizhilu.os.edu.dao.user.UserIntegralDao;
import com.yizhilu.os.edu.entity.user.LoginOnline;
import com.yizhilu.os.edu.entity.user.User;
import com.yizhilu.os.edu.entity.user.UserAccount;
import com.yizhilu.os.edu.entity.user.UserCode;
import com.yizhilu.os.edu.entity.user.UserExpand;
import com.yizhilu.os.edu.entity.user.UserExpandDto;
import com.yizhilu.os.edu.entity.user.UserIntegral;
import com.yizhilu.os.edu.entity.user.UserLoginLog;
import com.yizhilu.os.edu.entity.user.UserOptRecord;
import com.yizhilu.os.edu.service.card.CardCodeService;
import com.yizhilu.os.edu.service.order.ShopcartService;
import com.yizhilu.os.edu.service.order.TrxorderService;
import com.yizhilu.os.edu.service.user.LoginOnlineService;
import com.yizhilu.os.edu.service.user.UserAccountService;
import com.yizhilu.os.edu.service.user.UserCodeService;
import com.yizhilu.os.edu.service.user.UserExpandService;
import com.yizhilu.os.edu.service.user.UserIntegralService;
import com.yizhilu.os.edu.service.user.UserLoginLogService;
import com.yizhilu.os.edu.service.user.UserService;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service("userService")
public class UserServiceImpl
  implements UserService
{
  @Autowired
  private ShopcartService shopcartService;
  @Autowired
  UserIntegralDao userIntegralDao;
  private static final int HMAC_KEY_LEN = 60;
  MemCache memCache = MemCache.getInstance();
  @Autowired
  private UserDao userDao;
  @Autowired
  private UserExpandDao userExpandDao;
  @Autowired
  private UserAccountService userAccountService;
  @Autowired
  private UserCodeService userCodeService;
  @Autowired
  private TrxorderService trxorderService;
  @Autowired
  private UserExpandService userExpandService;
  @Autowired
  private UserIntegralService userIntegralService;
  @Autowired
  private GuidGeneratorService guidGeneratorService;
  @Autowired
  private UserLoginLogService userLoginLogService;
  @Autowired
  private LoginOnlineService loginOnlineService;
  @Autowired
  private CardCodeService cardCodeService;
  
  public Long addUser(User user)
  {
    generatePassword(user);
    user.setCreatedate(new Date());
    this.userDao.addUser(user);
    
    UserExpand userExpand = new UserExpand();
    userExpand.setCusId(user.getId());
    userExpand.setLastSystemTime(new Date());
    userExpand.setRegisterFrom(user.getRegisterFrom());
    this.userExpandDao.addUserExpand(userExpand);
    

    UserAccount userAccount = new UserAccount();
    userAccount.setUserId(user.getId());
    userAccount.setCreateTime(new Date());
    userAccount.setLastUpdateTime(new Date());
    userAccount.setBalance(new BigDecimal(0));
    userAccount.setForzenAmount(new BigDecimal(0));
    userAccount.setAccountStatus(AccountStatus.ACTIVE.toString());
    userAccount.setCashAmount(new BigDecimal(0));
    userAccount.setVmAmount(new BigDecimal(0));
    userAccount.setVersion(Long.valueOf(0L));
    this.userAccountService.addUserAccount(userAccount);
    

    UserIntegral userIntegral = new UserIntegral();
    userIntegral.setUserId(user.getId());
    userIntegral.setCurrentScore(Long.valueOf(0L));
    userIntegral.setTotalScore(Long.valueOf(0L));
    this.userIntegralDao.addUserIntegral(userIntegral);
    
    return user.getId();
  }
  
  public void deleteUserById(Long id)
  {
    this.userDao.deleteUserById(id);
  }
  
  public void updateUser(User user)
  {
    this.userDao.updateUser(user);
  }
  
  public String updateQueryUser(UserExpandDto queryUser)
    throws Exception
  {
    User u = getUserById(queryUser.getId());
    
    User user = new User();
    user.setId(queryUser.getId());
    user.setEmail(queryUser.getEmail());
    user.setNickname(queryUser.getNickname());
    user.setMobile(queryUser.getMobile());
    user.setUpdateEmail(queryUser.getUpdateEmail());
    if ((StringUtils.isNotEmpty(queryUser.getMobile())) && (!u.getMobile().equals(queryUser.getMobile())) && (getUserByMobile(user).intValue() > 0)) {
      return "mobileHave";
    }
    updateUser(user);
    
    UserExpand uex = this.userExpandService.getUserExpandByUserId(queryUser.getId());
    UserExpand userExpand = new UserExpand();
    userExpand.setCusId(queryUser.getId());
    userExpand.setGender(queryUser.getGender());
    userExpand.setRealname(queryUser.getRealname());
    userExpand.setAvatar(uex.getAvatar());
    userExpand.setUserInfo(queryUser.getUserInfo());
    userExpand.setRegisterFrom(uex.getRegisterFrom());
    this.userExpandService.updateUserExpand(userExpand);
    
    this.memCache.remove(MemConstans.USEREXPAND_INFO + queryUser.getId());
    return "success";
  }
  
  public String updateAppQueryUser(UserExpandDto queryUser)
    throws Exception
  {
    User u = getUserById(queryUser.getId());
    if ((queryUser.getNickname() != null) && (!queryUser.getNickname().equals("")))
    {
      User user = new User();
      user.setId(queryUser.getId());
      user.setNickname(queryUser.getNickname());
      updateUser(user);
    }
    UserExpandDto userExpandDto = this.userExpandService.getUserExpandByUid(queryUser.getId());
    if (queryUser.getGender() > -1) {
      userExpandDto.setGender(queryUser.getGender());
    }
    if ((queryUser.getRealname() != null) && (!queryUser.getRealname().equals(""))) {
      userExpandDto.setRealname(queryUser.getRealname());
    }
    if ((queryUser.getUserInfo() != null) && (!queryUser.getUserInfo().equals(""))) {
      userExpandDto.setUserInfo(queryUser.getUserInfo());
    }
    UserExpand userExpand = new UserExpand();
    userExpand.setCusId(userExpandDto.getId());
    userExpand.setGender(userExpandDto.getGender());
    userExpand.setRealname(userExpandDto.getRealname());
    userExpand.setAvatar(userExpandDto.getAvatar());
    userExpand.setUserInfo(userExpandDto.getUserInfo());
    userExpand.setRegisterFrom(userExpandDto.getRegisterFrom());
    this.userExpandService.updateUserExpand(userExpand);
    
    this.memCache.remove(MemConstans.USEREXPAND_INFO + queryUser.getId());
    return "success";
  }
  
  public void updateUserForIsavalibleById(User user)
  {
    this.userDao.updateUserForIsavalibleById(user);
  }
  
  public User getUserById(Long id)
  {
    return this.userDao.getUserById(id);
  }
  
  public void updatePwdById(User user, UserCode userCode)
  {
    generatePassword(user);
    this.userDao.updatePwdById(user);
    if (ObjectUtils.isNotNull(userCode))
    {
      userCode.setStatus(Long.valueOf(1L));
      this.userCodeService.updateUserCode(userCode);
    }
  }
  
  public List<User> getUserList(User user)
  {
    return this.userDao.getUserList(user);
  }
  
  public List<User> getUserListForLogin(User user)
  {
    return this.userDao.getUserListForLogin(user);
  }
  
  public List<User> getUserListForTelLogin(User user)
  {
    return this.userDao.getUserListForTelLogin(user);
  }
  
  public List<User> getUserListByCondition(User user, PageEntity page)
  {
    return this.userDao.getUserListByCondition(user, page);
  }
  
  public List<User> getUserListAndCourse(User user, PageEntity page)
  {
    return this.userDao.getUserListAndCourse(user, page);
  }
  
  private void generatePassword(User user)
  {
    String customerKey = StringUtils.getRandomString(60);
    String password = PurseSecurityUtils.secrect(user.getPassword(), customerKey);
    user.setPassword(password);
    user.setCustomerkey(customerKey);
  }
  
  public Map<String, Object> setLoginStatus(User user, String autoThirty, HttpServletRequest request, HttpServletResponse response)
  {
    Map<String, Object> map = new HashMap();
    try
    {
      UserExpandDto userExpandDto = queryUserExpand(user.getId().longValue());
      Long current = Long.valueOf(System.currentTimeMillis());
      userExpandDto.setCurrent(current.longValue());
      String uuid = StringUtils.createUUID().replace("-", "");
      

      SingletonLoginUtils.setLoginInfo(uuid, userExpandDto, autoThirty);
      if ((autoThirty != null) && (autoThirty.equals("true")))
      {
        this.memCache.set(MemConstans.USER_CURRENT_LOGINTIME + user.getId(), current.toString(), MemConstans.USER_AUTO_TIME);
        WebUtils.setCookie(response, "sid", uuid, 30);
        System.out.print("user sid"+uuid);
        WebUtils.setCookie(response, "sname", URLEncoder.encode(user.getEmail(), "UTF-8"), 30);
      }
      else
      {
        this.memCache.set(MemConstans.USER_CURRENT_LOGINTIME + user.getId(), current.toString(), MemConstans.USER_TIME);
        WebUtils.setCookie(response, "sid", uuid, 1);
        WebUtils.setCookie(response, "sname", URLEncoder.encode(user.getEmail(), "UTF-8"), 1);
      }
      this.shopcartService.addTempShopCart(request, response, user.getId());
      
      UserLoginLog userLoginLog = new UserLoginLog();
      userLoginLog.setLoginIp(WebUtils.getIpAddr(request));
      userLoginLog.setUserId(user.getId());
      userLoginLog.setLoginTime(new Date());
      String userAgent = UserAgentUtil.getUserAgent(request);
      if (StringUtils.isNotEmpty(userAgent))
      {
        userLoginLog.setUserAgent(userAgent.split(";")[0]);
        userLoginLog.setOsname(userAgent.split(";")[1]);
      }
      this.userLoginLogService.addUserLoginLog(userLoginLog);
      
      this.userIntegralService.addUserIntegral(IntegralKeyword.login.toString(), user.getId(), Long.valueOf(0L), Long.valueOf(0L), "");
      
      LoginOnline loginOnline = new LoginOnline();
      loginOnline.setUserId(user.getId());
      loginOnline.setLoginsid(uuid);
      loginOnline.setCreateTime(new Date());
      loginOnline.setType(ReqChanle.WEB.toString());
      this.loginOnlineService.addLoginOnline(loginOnline);
      if (UserExpandFrom.userCardFrom.toString().equals(userExpandDto.getRegisterFrom())) {
        this.cardCodeService.updateCardStatusByCode(user.getEmail());
      }
    }
    catch (Exception e)
    {
      e.printStackTrace();
    }
    return map;
  }
  
  public void updateUserAddress()
  {
    List<UserLoginLog> userLoginLogList = this.userLoginLogService.getUserLoginLogList();
    for (UserLoginLog userLoginLog : userLoginLogList) {
      try
      {
        this.userLoginLogService.updateUserLoginLog(userLoginLog);
      }
      catch (Exception e)
      {
        e.printStackTrace();
      }
    }
  }
  
  public List<User> getUserIsExsitByEmail(List<String> emails)
  {
    return this.userDao.getUserIsExsitByEmail(emails);
  }
  
  public void addUsers(List<User> users)
  {
    for (User user : users) {
      generatePassword(user);
    }
    this.userDao.addUsers(users);
  }
  
  public Integer getUserByMobile(User user)
    throws Exception
  {
    return this.userDao.getUserByMobile(user);
  }
  
  public String updateImportExcel(MultipartFile myFile)
    throws Exception
  {
    String msg = "";
    
    HSSFWorkbook wookbook = new HSSFWorkbook(myFile.getInputStream());
    HSSFSheet sheet = wookbook.getSheet("Sheet1");
    
    int rows = sheet.getLastRowNum();
    for (int i = 1; i <= rows + 1; i++)
    {
      HSSFRow row = sheet.getRow(i);
      if (row != null)
      {
        int maxcell = row.getLastCellNum();
        
        String email = getCellValue(row.getCell((short)0));
        if ((!ObjectUtils.isNull(email)) && (!email.equals("")))
        {
          if ((ObjectUtils.isNotNull(email)) && (StringUtils.isNotEmpty(email)))
          {
            Pattern emailRes = Pattern.compile("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
            Matcher mat = emailRes.matcher(email.toLowerCase());
            boolean emailF = mat.matches();
            if (!emailF)
            {
              msg = msg + "第" + i + "行邮箱格式错误<br/>";
              continue;
            }
          }
          String courseIds = getCellValue(row.getCell((short)1));
          String pwd = getCellValue(row.getCell((short)2));
          
          User trueUser = this.userDao.getUserIsExsitByEmail(email.toLowerCase());
          int count = 0;
          if (trueUser == null)
          {
            String uid = this.guidGeneratorService.gainCode("REG", false);
            User users = new User();
            users.setEmail(email.toLowerCase());
            users.setMobile(uid);
            if (StringUtils.isEmpty(pwd)) {
              users.setPassword("111111");
            } else {
              users.setPassword(pwd);
            }
            users.setRegisterFrom(UserExpandFrom.adminFrom.toString());
            addUser(users);
            
            this.userIntegralService.addUserIntegral(IntegralKeyword.register.toString(), users.getId(), Long.valueOf(0L), Long.valueOf(0L), "");
            trueUser = users;
          }
          if ((courseIds != null) && (!courseIds.equals("")))
          {
            String[] couArray = courseIds.replace(",", " ").trim().split(" ");
            for (count = 0; count < couArray.length; count++) {
              addOrderMsg(new Long(trueUser.getId().longValue()), couArray[count]);
            }
          }
        }
      }
    }
    return msg;
  }
  
  public void addOrderMsg(Long userId, String courseId)
    throws Exception
  {
    Map<String, String> sourceMap = new HashMap();
    sourceMap.put("type", "1");
    sourceMap.put("couponcode", "");
    sourceMap.put("userid", userId + "");
    sourceMap.put("reqchanle", ReqChanle.WEB.toString());
    sourceMap.put("reqIp", "");
    sourceMap.put("courseId", courseId);
    sourceMap.put("payType", "FREE");
    this.trxorderService.addFreeTrxorder(sourceMap);
  }
  
  public String getCellValue(HSSFCell cell)
  {
    String value = "";
    if (cell != null) {
      switch (cell.getCellType())
      {
      case 2: 
        break;
      case 0: 
        DecimalFormat df = new DecimalFormat("0");
        value = df.format(cell.getNumericCellValue());
        break;
      case 1: 
        value = cell.getStringCellValue().trim();
        break;
      default: 
        value = "";
      }
    }
    return value.trim();
  }
  
  public Integer getWebsiteRegNumber()
  {
    return this.userDao.getWebsiteRegNumber();
  }
  
  public void addUserOptRecord(Long userId, String type, Long optuser, String optusername, Long bizId, String desc)
  {
    UserOptRecord userOptRecord = new UserOptRecord();
    userOptRecord.setUserId(userId);
    userOptRecord.setType(type);
    userOptRecord.setBizId(bizId);
    userOptRecord.setOptuser(optuser);
    userOptRecord.setOptusername(optusername);
    userOptRecord.setDescription(desc);
    userOptRecord.setCreateTime(new Date());
    this.userDao.addUserOptRecord(userOptRecord);
  }
  
  public UserExpandDto queryUserExpand(long userId)
  {
    return this.userExpandDao.queryUserByid(Long.valueOf(userId));
  }
  
  public List<UserOptRecord> getUserOptRecordListByCondition(UserOptRecord userOptRecord, PageEntity page)
  {
    return this.userDao.getUserOptRecordListByCondition(userOptRecord, page);
  }
}


/* Location:           D:\licai\kuaijidao\web\WEB-INF\lib\demo_web_v25.jar
 * Qualified Name:     com.yizhilu.os.edu.service.impl.user.UserServiceImpl
 * JD-Core Version:    0.7.0.1
 */